package com.cn.kabalifeuser.ui.order.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telecom.Call;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.callback.SchedulerTransformer;
import com.cn.kabalifeuser.config.Constants;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.event.RxBus;
import com.cn.kabalifeuser.event.RxBusBean;
import com.cn.kabalifeuser.ui.integral.bean.WxPayBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.my.activity.OrderListAcivity;
import com.cn.kabalifeuser.ui.order.adapter.OrderDetailsAdapter;
import com.cn.kabalifeuser.ui.order.bean.OrderDetailsBean;
import com.cn.kabalifeuser.ui.release.bean.PayResult;
import com.cn.kabalifeuser.ui.release.bean.ZfbBean;
import com.cn.kabalifeuser.utils.GsonUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.cn.kabalifeuser.view.dialogView.PayErrDialog;
import com.flyco.roundview.RoundTextView;
import com.kongzue.dialog.v2.SelectDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by 晓林 on 2020/9/21.
 * function:
 */
public class MallOrderDetailsActivity extends IBaseActivity<MallOrderDetailsView, MallOrderDetailsPresenter> implements MallOrderDetailsView, CommonPopupWindow.ViewInterface {


    Bundle bundle;
    int id;
    int sign;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_original_price)
    TextView tvOriginalPrice;
    @BindView(R.id.tv_postage)
    TextView tvPostage;
    @BindView(R.id.tvdiscount)
    TextView tvdiscount;
    @BindView(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R.id.tv_created_at)
    TextView tvCreatedAt;
    @BindView(R.id.tv_ok_time)
    TextView tvOkTime;
    @BindView(R.id.tv_btn_colce)
    RoundTextView tvBtnColce;
    @BindView(R.id.tv_btn_pay)
    RoundTextView tvBtnPay;
    @BindView(R.id.tv_btn_logistics)
    RoundTextView tvBtnLogistics;
    @BindView(R.id.tv_btn_confirm)
    RoundTextView tvBtnConfirm;
    @BindView(R.id.tv_btn_comment)
    RoundTextView tvBtnComment;
    @BindView(R.id.tv_btn_shouhou)
    RoundTextView tvBtnShouhou;


    List<OrderDetailsBean.ResultBean.GoodsInfoBean> mList;
    OrderDetailsAdapter mAdapter;


    private CommonPopupWindow popupWindowPay;

    OrderDetailsBean orderDetailsBean;

    @Override
    protected MallOrderDetailsPresenter createPresenter() {
        return new MallOrderDetailsPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mall_order_details;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        bundle = getIntent().getExtras();
        id = bundle.getInt("id");
        sign = bundle.getInt("sign");
        setTitleBar("订单详情");
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);
        rvData.setLayoutManager(layoutManager3);
        rvData.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new OrderDetailsAdapter(R.layout.order_list_item, mList);
        //给RecyclerView设置适配器
        rvData.setAdapter(mAdapter);
        mPresenter.onOrderDetailsData(LoginHelper.getLonginData().getResult(), id, sign == 0 ? 1 : 2);

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean.class)
                .compose(new SchedulerTransformer<RxBusBean>())
                .subscribe(new Action1<RxBusBean>() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void call(RxBusBean rxBusBean) {
                        if (rxBusBean.getSign() == 1111 && rxBusBean.getId() == 1111) {
                            //详情操作成功以后。
                            mPresenter.onOrderDetailsData(LoginHelper.getLonginData().getResult(), id, sign == 0 ? 1 : 2);
                        } else if (rxBusBean.getId() == 2003 && rxBusBean.getSign() == 2003) {
                            RxToast.success("支付成功");
                            Constants.PAY_SIGN = 0;
                            mPresenter.onOrderDetailsData(LoginHelper.getLonginData().getResult(), id, sign == 0 ? 1 : 2);
                        }
                    }
                });

    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onOrderDetailsSuccess(OrderDetailsBean bean) {
        orderDetailsBean = bean;
        tvNum.setText(bean.getResult().getNum());
        tvOriginalPrice.setText(bean.getResult().getOriginal_price());
        tvPostage.setText(bean.getResult().getPostage());
        tvdiscount.setText(String.valueOf(bean.getResult().getDiscount()));
        tvTotalAmount.setText(bean.getResult().getTotal_amount());
        tvCreatedAt.setText(bean.getResult().getCreated_at());
        tvOkTime.setText(bean.getResult().getOk_time());
        mAdapter.replaceData(bean.getResult().getGoods_info());
// 0：已取消，1：待支付，2：已支付，3：退款，4:待收货，5：已完成
        if (bean.getResult().getGoods_info().get(0).getStatus() == 0) {
            tvBtnColce.setVisibility(View.GONE);
            tvBtnPay.setVisibility(View.GONE);
            tvBtnLogistics.setVisibility(View.GONE);
            tvBtnConfirm.setVisibility(View.GONE);
            tvBtnComment.setVisibility(View.GONE);
            tvBtnShouhou.setVisibility(View.GONE);
        } else if (bean.getResult().getGoods_info().get(0).getStatus() == 1) {
            tvBtnColce.setVisibility(View.VISIBLE);
            tvBtnPay.setVisibility(View.VISIBLE);
            tvBtnLogistics.setVisibility(View.GONE);
            tvBtnConfirm.setVisibility(View.GONE);
            tvBtnComment.setVisibility(View.GONE);
            tvBtnShouhou.setVisibility(View.GONE);
        } else if (bean.getResult().getGoods_info().get(0).getStatus() == 2) {
            tvBtnColce.setVisibility(View.VISIBLE);
            tvBtnPay.setVisibility(View.GONE);
            tvBtnLogistics.setVisibility(View.GONE);
            tvBtnConfirm.setVisibility(View.GONE);
            tvBtnComment.setVisibility(View.GONE);
            if (bean.getResult().getGoods_info().get(0).getIs_sale() == 0) {
                tvBtnShouhou.setVisibility(View.VISIBLE);
                tvBtnShouhou.setText("申请售后");
            } else {
                tvBtnShouhou.setVisibility(View.GONE);
            }


        } else if (bean.getResult().getGoods_info().get(0).getStatus() == 3) {
            tvBtnColce.setVisibility(View.GONE);
            tvBtnPay.setVisibility(View.GONE);
            tvBtnLogistics.setVisibility(View.GONE);
            tvBtnConfirm.setVisibility(View.GONE);
            tvBtnComment.setVisibility(View.GONE);
            tvBtnShouhou.setVisibility(View.GONE);
        } else if (bean.getResult().getGoods_info().get(0).getStatus() == 4) {
            tvBtnColce.setVisibility(View.GONE);
            tvBtnPay.setVisibility(View.GONE);
            tvBtnLogistics.setVisibility(View.VISIBLE);
            tvBtnConfirm.setVisibility(View.VISIBLE);
            tvBtnComment.setVisibility(View.GONE);
            if (bean.getResult().getGoods_info().get(0).getIs_sale() == 0) {
                tvBtnShouhou.setVisibility(View.VISIBLE);
                tvBtnShouhou.setText("申请售后");
            } else {
                tvBtnShouhou.setVisibility(View.GONE);
            }
        } else if (bean.getResult().getGoods_info().get(0).getStatus() == 5) {
            tvBtnColce.setVisibility(View.GONE);
            tvBtnPay.setVisibility(View.GONE);
            tvBtnLogistics.setVisibility(View.GONE);
            tvBtnConfirm.setVisibility(View.GONE);
            if (bean.getResult().getGoods_info().get(0).getIs_sale() == 0) {
                tvBtnShouhou.setVisibility(View.VISIBLE);
                tvBtnShouhou.setText("申请售后");
            } else {
                tvBtnShouhou.setVisibility(View.GONE);
            }
            if (bean.getResult().getGoods_info().get(0).getIs_review() == 0) {
                tvBtnComment.setVisibility(View.VISIBLE);
            } else {
                tvBtnComment.setVisibility(View.GONE);
            }
        }

    }

    @Override
    public void onOrderSetSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());
        finish();
        RxBus.getDefault().post(new RxBusBean(1111, 1111));
    }

    @Override
    public void onOrderPaySuccess(String json) {
        if (paySign == 2) {
            //todo 支付宝
            ZfbBean bean = GsonUtil.GsonToJsonClass(json, ZfbBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                //TODO 支付宝支付
                final String orderInfo = bean.getResult();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(
                                MallOrderDetailsActivity.this);
                        Map<String, String> result = alipay
                                .payV2(orderInfo, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());
        } else if (paySign == 1) {
            //todo 微信
            WxPayBean bean = GsonUtil.GsonToJsonClass(json, WxPayBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                Constants.PAY_SIGN = 2002;
                IWXAPI api = WXAPIFactory.createWXAPI(getMe(), bean.getResult().getAppid());
                api.registerApp(bean.getResult().getAppid());
                PayReq req = new PayReq();
                req.appId = bean.getResult().getAppid();
                req.partnerId = bean.getResult().getPartnerid();  //商户id
                req.prepayId = bean.getResult().getPrepayid(); //预支付交易会话ID
                req.packageValue = bean.getResult().getPackageX(); //扩展字段
                req.nonceStr = bean.getResult().getNoncestr(); //随机字符串
                req.timeStamp = String.valueOf(bean.getResult().getTimestamp());//时间戳
                req.sign = bean.getResult().getSign(); //签名
                api.sendReq(req);
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());

        }
    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        LoggerUtils.d("支付宝支付成功咯~~~");
                        RxToast.success("支付成功");
                        if (popupWindowPay != null)
                            popupWindowPay.dismiss();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LoggerUtils.d("支付宝支付失敗了~~~");
                        RxToast.error("支付失败!");

                    }
                    break;
                }
                default:
                    break;
            }
        }


    };

    /**
     * zhifu
     */
    private void showPay() {
        if (popupWindowPay != null && popupWindowPay.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_commodity_pay, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowPay = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_commodity_pay)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowPay.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }


    int paySign = 1;

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            //todo 支付
            case R.layout.pw_commodity_pay:
                ImageView img_check_weixin = view.findViewById(R.id.img_check_weixin);
                ImageView img_check_zfb = view.findViewById(R.id.img_check_zfb);
                img_check_weixin.setImageResource(R.drawable.check_true);
                img_check_zfb.setImageResource(R.drawable.check_false);
                paySign = 1;
                view.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Constants.PAY_SIGN = 0;
                        if (popupWindowPay != null)
                            popupWindowPay.dismiss();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_zfb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_false);
                        img_check_zfb.setImageResource(R.drawable.check_true);
                        paySign = 2;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_weixin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_true);
                        img_check_zfb.setImageResource(R.drawable.check_false);
                        paySign = 1;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_qianbao).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_yinlian).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.tv_btn_pay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.onOrderPayData(LoginHelper.getLonginData().getResult(), orderDetailsBean.getResult().getId(), paySign
                        );

                    }
                });
                break;
        }
    }


    @OnClick({R.id.tv_btn_shouhou, R.id.tv_btn_colce, R.id.tv_btn_pay, R.id.tv_btn_logistics, R.id.tv_btn_confirm, R.id.tv_btn_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_btn_shouhou:
                //todo 售后
                if (orderDetailsBean.getResult().getGoods_info().get(0).getIs_sale() == 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("id", orderDetailsBean.getResult().getGoods_info().get(0).getId());
                    $startActivity(AfterSaleActivity.class, bundle);
                } else RxToast.info("处理中");


                break;
            case R.id.tv_btn_colce:
                //todo 取消
                SelectDialog.show(getMe(), "提示", "确定要取消该订单吗？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.onOrderSetData(LoginHelper.getLonginData().getResult(), 0, orderDetailsBean.getResult().getId());
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
            case R.id.tv_btn_pay:
                //todo 支付
                showPay();
                break;
            case R.id.tv_btn_logistics:
                //todo 物流
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                $startActivity(IExpressActivity.class, bundle);
                break;
            case R.id.tv_btn_confirm:
                //todo 确认收货
                SelectDialog.show(getMe(), "提示", "确定要收货吗？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.onOrderSetData(LoginHelper.getLonginData().getResult(), orderDetailsBean.getResult().getId());
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
            case R.id.tv_btn_comment:
                //todo 评价
                bundle = new Bundle();
                bundle.putString("s_Good_img", orderDetailsBean.getResult().getGoods_info().get(0).getGood_img());
                bundle.putString("s_Title", orderDetailsBean.getResult().getGoods_info().get(0).getTitle());
                bundle.putString("s_Spec_key", orderDetailsBean.getResult().getGoods_info().get(0).getSpec_key());
                bundle.putString("s_Original_price", orderDetailsBean.getResult().getGoods_info().get(0).getOriginal_price());
                bundle.putInt("s_Good_num", orderDetailsBean.getResult().getGoods_info().get(0).getGood_num());
                bundle.putInt("id", orderDetailsBean.getResult().getId());
                bundle.putString("s_Created_at", orderDetailsBean.getResult().getGoods_info().get(0).getCreated_at());
                $startActivity(CommentAddActivity.class, bundle);
                break;
        }
    }
}
